package com.ciei.dpagm.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.ciei.dpagm.util.APP;
import com.ciei.dpagm.util.DateUtil;
import com.ciei.dpagm.util.PageParam;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class BaseController {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 返回所有参数
	 * 
	 * @return
	 */
	protected Map<String, String[]> getAllRequestParams() {
		HttpServletRequest request = getHttpServletRequest();
		return request.getParameterMap();
	}

    protected PageParam getPageParams(){
    	PageParam pageParam=new PageParam();
    	Map<String, Object> params = new HashMap<String, Object>();
    	HttpServletRequest request = getHttpServletRequest();
    	Enumeration<String> paramterNames = request.getParameterNames();
    	if(paramterNames != null) {
    		for(Enumeration<String> e = paramterNames; e.hasMoreElements();){
    			String paraName=e.nextElement().toString();
    			params.put(paraName, request.getParameter(paraName));
    		}
    	}
    	
    	pageParam.posStart = Integer.valueOf(request.getParameter("posStart") == null ? "0" : request.getParameter("posStart"));
    	pageParam.count = Integer.valueOf(request.getParameter("count") == null ? "30" : request.getParameter("count"));
    	pageParam.params=params;
    	
    	return pageParam;
    }

	protected PageParam getPageParams(JSONObject pageParamsJson) {
		PageParam pageParam = new PageParam();
		if (pageParamsJson != null && pageParamsJson.size() > 0) {
			Integer currentPage = pageParamsJson.getInteger(APP.CURRENT_PAGE);
			if (currentPage != null) {
				pageParam.setCurrentPage(currentPage);
			} else {
				pageParam.setCurrentPage(1);
			}

			Integer pageSize = pageParamsJson.getInteger(APP.PAGE_SIZE);
			if (pageSize != null) {
				pageParam.setPageSize(pageSize);
			} else {
				pageParam.setPageSize(30);
			}

			Map<String, Object> params = pageParamsJson.getJSONObject(APP.PARAMS);
			if (params != null) {
				pageParam.setParams(params);
			}

			Map<String, Object> sort = pageParamsJson.getJSONObject(APP.SORT);
			if (sort != null) {
				pageParam.getSort().putAll(sort);
			}
		}
		return pageParam;
	}
    
	/**
	 * 获取request
	 * 
	 * @return HttpServletRequest
	 */
	protected HttpServletRequest getHttpServletRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	protected void clearSessionKey(String sessionKey) {
		getHttpServletRequest().getSession().removeAttribute(sessionKey);
	}

	protected void putSessionKey(String sessionKey, Object value) {
		getHttpServletRequest().getSession().setAttribute(sessionKey, value);
	}
	
	protected String getSessionId() {
		return getHttpServletRequest().getSession().getId();
	}
	
	protected Object findSessionKey(String sessionKey) {
		return getHttpServletRequest().getSession().getAttribute(sessionKey);
	}

	protected Object getSessionUser() {
		return SecurityUtils.getSubject().getPrincipal();
	}

	protected boolean isLogin() {
		return getSessionUser() == null ? false : true;
	}
	
	public <T> T getInstanceByParameters(Class<T> className) {//通过反射得到对象，set方法和get方法，属性，属性通过request.getParameter()设值
		try {
			HttpServletRequest request = getHttpServletRequest();//得到当前请求
			T obj = className.newInstance();//得到className的对象
			Method[]  methods = className.getMethods();//得到当前类的所有方法，存储在方法数组中
			String field;//声明字段
			String fieldType;//声明字段类型
			Method methodSet;//生命set方法
			for(Method method:methods){//遍历方法数组
			   if(method.getName().startsWith("get")) {//判断方法名是否以get起始
			      try {
			    	  //先通过getDeclaredField得到字段而后通过getName()方法的到字段的字符串表示
			    	  field=className.getDeclaredField(method.getName().substring(3, 4).toLowerCase()+method.getName().substring(4)).getName();
			    	  //getMethod的第一个参数是set方法名，第二个参数是get方法的返回类型，通过这个方法可以得到类的set方法
			    	  methodSet=className.getMethod("set" + method.getName().substring(3),method.getReturnType());
			      }catch (NoSuchMethodException e) {
			    	  continue;
			      }catch (NoSuchFieldException e) {
					  continue;
				  }
			      fieldType = method.getReturnType().getSimpleName();//得到get方法的返回类型的字符串表示
			      String paraField=request.getParameter(field);//从参数的得到接下来要赋予字段的值
                  if(paraField!=null && !paraField.equals("null") &&!paraField.isEmpty()) {//如果参数中未携带该字段或者该字段值为空字符串
			    	  if(fieldType.equals(String.valueOf("Integer"))) {
				    	  methodSet.invoke(obj, Integer.parseInt(request.getParameter(field)));//通过调用invoke()方法给实例化的类赋值
				      }else if(fieldType.equals(String.valueOf("String"))) {
				    	  methodSet.invoke(obj, request.getParameter(field)); 
				      }else if(fieldType.equals(String.valueOf("Float"))) {
				    	  methodSet.invoke(obj, Float.valueOf(request.getParameter(field)));
				      }else if(fieldType.equals(String.valueOf("Double"))) {
				    	  methodSet.invoke(obj, Double.valueOf(request.getParameter(field)));
				      }else if(fieldType.equals(String.valueOf("Timestamp"))) {
				    	  int timestampLength=paraField.length();//判断时间格式
				    	  switch(timestampLength){
				    	  case 7:methodSet.invoke(obj, DateUtil.stringToTimestamp(request.getParameter(field), DateUtil.FORMAT_MONTH));
				    	  break;
				    	  case 8:methodSet.invoke(obj, DateUtil.stringToTimestamp(request.getParameter(field), DateUtil.FORMAT_SHORT_CLEAN));
				    	  break;
				    	  case 10:methodSet.invoke(obj, DateUtil.stringToTimestamp(request.getParameter(field), DateUtil.FORMAT_SHORT));
				    	  break;
				    	  case 11:methodSet.invoke(obj, DateUtil.stringToTimestamp(request.getParameter(field), DateUtil.FORMAT_SHORT_CN));
				    	  break;
				    	  case 14:methodSet.invoke(obj, DateUtil.stringToTimestamp(request.getParameter(field), DateUtil.FORMAT_LONG_CLEAN));
				    	  break;
				    	  case 16:methodSet.invoke(obj, DateUtil.stringToTimestamp(request.getParameter(field), DateUtil.FORMAT_LONG_NS));
				    	  break;
				    	  case 17:methodSet.invoke(obj, DateUtil.stringToTimestamp(request.getParameter(field), DateUtil.FORMAT_FULL_CLEAN));
				    	  break;
				    	  case 19:methodSet.invoke(obj, DateUtil.stringToTimestamp(request.getParameter(field), DateUtil.FORMAT_LONG));
				    	  break;
				    	  case 21:methodSet.invoke(obj, DateUtil.stringToTimestamp(request.getParameter(field), DateUtil.FORMAT_LONG_CN));
				    	  break;
				    	  case 23:methodSet.invoke(obj, DateUtil.stringToTimestamp(request.getParameter(field), DateUtil.FORMAT_FULL));
				    	  break;
				    	  case 26:methodSet.invoke(obj, DateUtil.stringToTimestamp(request.getParameter(field), DateUtil.FORMAT_FULL_CN));
				    	  break;
				    	  default:break;
				    	  }
				      }
			      }
                  
			   }
			}
			return obj;	
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}  catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
	}
	
}
